const { login } = require('../controler/user')
const { set } = require('../database/redis')
const { SuccessModel, ErrorModel } = require('../model/Resmodel')

const getCookieExpires = () => {
  let d = new Date()
  d.setTime(d.getDate() + (48 * 60 * 60 * 1000)) //这个意思是重新设置当前的时间开始的过期时间
  return d.toUTCString() //就是cookie格式的时间表示
}

const HandleUserRouter = (req, res) => {
  let method = req.method
  if (method === 'POST' && req.path === '/api/user/login') {
    const { username, password } = JSON.parse(JSON.parse(req.body))
    // const { username, password } = req.query
    // var username = JSON.parse(req.body.username)
    // var password = JSON.parse(req.body.password)

    const reslogin = login(username, password)
    return reslogin.then(datas => {

      if (datas.username) {

        //设置session
        req.session.username = datas.username
        req.session.realname = datas.realname
        set(req.sessionId, req.session)

        return new SuccessModel()
      }
      return new ErrorModel('登录失败')

    })


  }


  // if (method === 'GET' && req.path === '/api/user/login-test') {
  //   if (req.session.username) {
  //     return Promise.resolve((new SuccessModel({
  //       session: req.session.username
  //     })))
  //   }
  //   return Promise.resolve(new ErrorModel('尚未登录'))
  // }
}

module.exports = HandleUserRouter